//
//  YZMWebViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/5.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMWebViewController.h"
#import "YZRequestURLs.h"
#import "YZMResultView.h"
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import <MJRefresh/MJRefresh.h>
#import "YZMHomeBannerModel.h"
#import "YZMWebViewService.h"
#import "YZMCustomURLProtocol.h"

@implementation YZMWebViewController{
    
    NSString *_urlString;
    NSArray *_paramArray;
    BOOL _type; /*0：非完整网址（默认）  1：完整网址*/
    
    int _pageCount;
    
    BOOL _hasAppearFlag;
    
    NSString *_savedTitle;
    
    YZMResultView *_resultView;
    NSString *_backPageName;
    
    BOOL _finishFlag;
    NSDictionary *_eventDic;
    UIButton *_submitButton;
    NSDictionary *_rightDic;
    NSString *_urlStr;
    NSString *_schemeStr;
}

-(UIWebView *)webView{
    return _webView;
}

- (id)init{
    
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    self.title = _savedTitle;
    if ([_urlString isEqualToString:@"app/index.html#/simulateStock"] && _pageCount != 0) {
    
        _urlStr = [_webView.request.URL.absoluteString stringByAppendingFormat:@"&v=%d",rand()];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.title = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
//    [NSURLProtocol registerClass:[YZMCustomURLProtocol class]];
    //创建右侧按钮
    if (_rightDic) {
        
        if (_rightDic[@"title"]) {
            
            self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:_rightDic[@"title"] target:self action:@selector(rightBtnMethod)];

        } else {
            
            self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:_rightDic[@"image"] target:self action:@selector(rightBtnMethod)];
        }
    }
    
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self initWebView];
    
    _resultView = [YZMResultView new];
    [self.view addSubview:_resultView];
    [_resultView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.center.equalTo(self.view);
        maker.width.equalTo(self.view);
    }];
    
    __weak __typeof(&*self) weakSelf = self;
    _resultView.retryAction = ^{
      
        [weakSelf initLoad];
    };
    
    [self initLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

- (void)reachabilityChanged:(NSNotification *)note{
    if (!kNetworkNotReachability && !_finishFlag) {
        
        [self initLoad];
    }
}

- (BOOL)shouldAutoBackToPreviousController{
    
    if ([_urlStr containsString:_webView.request.URL.absoluteString] && _urlStr.length > _webView.request.URL.absoluteString.length) {
        
        return YES;
    }
    
    if ([_webView canGoBack]) {
        
        [_webView goBack];
        _pageCount -= 1;
        
        //显示按钮
        if (_eventDic && _pageCount == 1) {
            
            [self webViewAutoLayout];
        }
        return NO;
    }
    
    if (_backPageName.length != 0) {
        
        [YZMHCMInstance popViewControllerBeforeControllerName:_backPageName animated:YES];
        return NO;
    }
    
    return YES;
}


- (void)initWebView{
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _webView.backgroundColor = [UIColor clearColor];
    _webView.opaque = NO;
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    _webView.scrollView.scrollEnabled = YES;
    _webView.scrollView.bounces = NO;
    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        if (_eventDic && _pageCount == 0) {
            maker.top.left.right.equalTo(self.view);
            maker.bottom.equalTo(self.view).offset(-70);
        } else {
            maker.top.left.right.bottom.equalTo(self.view);
        }
    }];
    
    for (UIView *iv in _webView.subviews) {
        for (id v in iv.subviews) {
            if ([v isKindOfClass:NSClassFromString(@"UIWebBrowserView")]) {
                UIView *v1 = (UIView *)v;
                for (UIGestureRecognizer *gesture in v1.gestureRecognizers) {
                    if ([gesture isKindOfClass:NSClassFromString(@"UITapGestureRecognizer")]) {
                        gesture.delegate = self;
                        break;
                    }
                }
            }
        }
    }
}

- (void)initLoad{
    
    _finishFlag = NO;
    
    _pageCount = 0;
    
    if (_type == 1) {
        
        NSURL *url = [NSURL URLWithString:_urlString];
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
        [_webView loadRequest:request];
        
        return;
    }
    
    //处理非完整URL
    [self urlProcess:_urlString];
}

- (void)urlProcess:(NSString *)urlString {
    
    NSString *paramString = [NSString string];
    
    for (NSDictionary *dic in _paramArray) {
        
        paramString = [paramString stringByAppendingFormat:@"%@=%@&", [dic objectForKey:sYZMWebviewParamName], [dic objectForKey:sYZMWebviewParamValue]];
    }
    
    paramString = [paramString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&"]];
    
    NSString *webURLString = @"";
    if (![urlString hasPrefix:@"http"]) {
        
        webURLString = URL_BASE_STRING;
        webURLString = [webURLString stringByAppendingPathComponent:urlString];
    } else {
        
        webURLString = urlString;
    }
    
    if (![webURLString hasSuffix:urlString]) {
        
        webURLString = [webURLString stringByAppendingString:@"/"];
    }
    
    if (paramString && paramString.length != 0) {
        
        webURLString = [webURLString stringByAppendingFormat:@"?%@",paramString];
    }
    
    NSURL *url;
    NSMutableURLRequest *request;
    if ([urlString containsString:@"kuaisuPay"]) {
        NSString *str = [NSString stringWithFormat:@"%@",[urlString stringByReplacingOccurrencesOfString:@"kuaisuPay" withString:@""]];
        url = [NSURL URLWithString:str];
        request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:8];
        request.HTTPMethod = @"POST";
        [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        request.HTTPBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
    }else{
        url = [NSURL URLWithString:[webURLString stringByAppendingFormat:@"&v=%d",rand()]];
        request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
    }
    
    [_webView loadRequest:request];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    _finishFlag = YES;
    _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
    
    if (_pageCount == 1) {
        
        self.title = _savedTitle;
        
        if (_eventDic && !_submitButton) { //创建跳转按钮
            
            [self createBtn];
        }
    }else{
        
        NSString *titleString = [webView stringByEvaluatingJavaScriptFromString: @"document.title"];
        
        NSArray *titleArray = [titleString componentsSeparatedByString:@"-"];
        
        if (!titleArray || titleArray.count == 0 ) {
            
            self.title = _savedTitle;
            
        }else{
            
            self.title = [titleArray[titleArray.count -1] trimSpace];
        }
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    _resultView.status = YZM_RESULT_STATUS_FOR_LOADING;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    _finishFlag = NO;
    self.title = @"加载失败";
    if (kNetworkNotReachability) {
        
        _resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
        
        return;
    }
    
    if ([_schemeStr isEqualToString:@"yztz"]) {
        return;
    }
    
    _resultView.status = YZM_RESULT_STATUS_FOR_ABNORMAL;
}

- (void)retryForNoWifi{
    
    [self initLoad];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
//    NSHTTPCookie *cookie;
//    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    for (cookie in [storage cookies])
//    {
//        [storage deleteCookie:cookie];
//    }
    
    _webView.delegate = nil;
    [_webView removeFromSuperview];
    _webView = nil;
    
    _paramArray = nil;
    [NSURLProtocol unregisterClass:[YZMCustomURLProtocol class]];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    //显示/隐藏按钮
    if (_eventDic && _pageCount == 1) {
        
        [self webViewAutoLayout];
    }
    
    _schemeStr = request.URL.scheme;
#ifdef YZMicroStock
#else
    NSURL *url = request.URL;
    if ([_schemeStr isEqualToString:@"yztz"]) {
        
        NSString *bundleID = [[[[NSBundle mainBundle] bundleIdentifier] componentsSeparatedByString:@"."] lastObject];
        NSString *newUrlStr = [NSString stringWithFormat:@"%@://%@%@", bundleID, url.host, url.path];
        if (request.URL.query) {
            
            newUrlStr = [newUrlStr stringByAppendingFormat:@"?%@", url.query];
        }
        
        url = [NSURL URLWithString:newUrlStr];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
            
            return NO;
        }
    }
#endif
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        
        _pageCount += 1;
        
        _hasAppearFlag = YES;
        
    }else if(navigationType == UIWebViewNavigationTypeBackForward){
        
        _pageCount -= 1;
        
    }else if (navigationType == UIWebViewNavigationTypeOther){
        
        _pageCount += 1;
    }
    
    return YES;
}

#pragma mark -- private Method

- (void)rightBtnMethod {

    SEL selector = NSSelectorFromString(_rightDic[@"selector"]);
    if ([[YZMWebViewService sharedService] respondsToSelector:selector]) {
        
        IMP imp = [[YZMWebViewService sharedService] methodForSelector:selector];
        void (*func)(id, SEL) = (void *)imp;
        func([YZMWebViewService sharedService], selector);
    }
}

- (void)createBtn {
    
    WS(ws)
    UIView *bottomView = [UIView new];
    bottomView.tag = 101;
    bottomView.backgroundColor = [YZMAppStyle colorForLabelMark];
    bottomView.layer.borderWidth = 0.5;
    bottomView.layer.borderColor = [YZMAppStyle colorForSplitLine].CGColor;
    [self.view addSubview:bottomView];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(ws.view).offset(2);
        make.left.equalTo(ws.view).offset(-2);
    }];
    
    _submitButton = [YZMAppStyle submitButton];
    _submitButton.enabled = YES;
    [_submitButton setTitle:_eventDic[@"btnName"] forState:UIControlStateNormal];
    [_submitButton addTarget:self action:@selector(moveToNextPage:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:_submitButton];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(bottomView).insets(UIEdgeInsetsMake(15, 15, 15, 15));
    }];
}

- (void)moveToNextPage:(UIButton *)send {
    
    [YZMHomeBannerModel selectDirection:_eventDic withLocal:NO];
}

- (void)webViewAutoLayout {
    
    UIView *bottomView = [self.view viewWithTag:101];
    bottomView.hidden = !bottomView.isHidden;
    [_webView mas_updateConstraints:^(MASConstraintMaker *maker){
        
        if (_eventDic && bottomView.isHidden) {
            
            maker.top.left.right.bottom.equalTo(self.view);
        } else {
            
            maker.top.left.right.equalTo(self.view);
            maker.bottom.equalTo(self.view).offset(-70);
        }
    }];
}

#pragma mark -- Params Manager

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMWebViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams:(NSDictionary *)params{
    
    _urlString = params[@"urlString"];
    _savedTitle = params[@"title"];
    _type = [params[@"type"] boolValue];
    _pageCount = 0;
    _backPageName = params[@"backPageName"];
    _eventDic = params[@"urlEvent"];
    _rightDic = params[@"rightDic"];
    
    if (!_type) {
        
        _paramArray = params[@"webParams"];
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
   CGPoint point = [touch locationInView:[touch view]];
    if (point.x >= 0 &&  point.x <= 44 && point.y >= 0 && point.y <= 44) {
        if (![_webView canGoBack]) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    return YES;
}


@end
